<template>
  <div class="flex h-full">
    <div class="w-85 h-full p-4 flex-shrink-0 border-r flex flex-col border-gray-200 overflow-y-auto">
      <a-input class="mb-4" v-model:value.trim="state.searchName" placeholder="请输入搜索关键字" allow-clear @change="getFolderTree">
        <template #suffix v-if="!state.searchName.length">
          <SearchOutlined style="color: #999" />
        </template>
      </a-input>
      <a-tree
        v-if="state.treeData.length > 0"
        v-model:selectedKeys="state.selectedKeys"
        class="tree-warpper"
        :block-node="true"
        :tree-data="state.treeData"
        show-icon
        default-expand-all
        @select="handleNodeSelect"
      >
        <template #title="{ name, data }">
          <div class="title-warpper">
            <span>{{ name }}</span>
            <span class="title-btn space-x-2 pr-2">
              <EditOutlined v-if="data.parentId" @click.stop="handleEdit(data)" />
              <a-popconfirm v-if="data.parentId" ok-text="确定" cancel-text="取消" @confirm="handleDelete(data)">
                <template #title>
                  <p>是否确认删除？</p>
                </template>
                <MinusCircleOutlined @click.stop="null" />
              </a-popconfirm>
              <PlusCircleOutlined @click.stop="handleAdd(data)" />
            </span>
          </div>
        </template>
      </a-tree>
    </div>
    <div class="px-4" :style="{ width: 'calc(100% - 340px)' }">
      <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
      <DynamicTable :tables="dyTable" :config="dyTableConfig" ref="directoryRef">
        <!--状态-->
        <template #stateSwitch="{ record }">
          <a-switch :checked="record.status" checked-children="开" un-checked-children="关" :checked-value="1" :un-checked-value="0" @change="(value) => statusChange(record, value)" />
        </template>
      </DynamicTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { createVNode, getCurrentInstance, onBeforeUnmount, reactive, ref } from 'vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { Api, typeAdd, typeUpdateStatus, typeTree, typeDelete, typeGet, typeUpdate } from '@/config/api/archives';
import { MinusCircleOutlined, PlusCircleOutlined, EditOutlined, MoreOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { DYNAMICLAYERFORM, DYNAMICLAYERCLEAR, LOCALSUBSERVE, RESETTABLE } from '@/mixins/subject/subject-types';
import { filter } from 'rxjs/operators';
import indexService from './index.service';
import { CODE_RULE, generateCode } from '@/config/api/authorityManage';

const state = reactive({
  searchName: '',
  selectedKeys: [],
  treeData: [],
  selectParentId: ''
});
const directoryRef = ref(null);
const { proxy }: any = getCurrentInstance();
const dyConfig: any = {
  queryUrl: Api.typePage,
  labelCol: 6,
  wrapperCol: 18,
  grid: 8, // 分栏
  style: 'table-form',
  cancelSave: true, // 隐藏底部按钮
  combinationMethod(msg) {
    return Object.assign(msg, { parentId: state.selectParentId });
  }
};
const dyAddConfig: any = {
  name: 'archiveType',
  type: 'layer',
  width: '424px',
  title: '添加档案类型',
  labelCol: 24,
  wrapperCol: 24,
  layout: 'vertical',
  localSub: true,
  data: {}
};
const dyTableConfig: any = {
  name: 'archiveType',
  queryUrl: Api.typePage,
  protType: 'post',
  isScreen: true
};
const dyQuestions: any = reactive(indexService.getQuestions());
const dyTable: any = reactive(indexService.getTables());
const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === LOCALSUBSERVE && item.state.name == dyAddConfig.name) {
      const params = { ...item.value };
      const fun = !item.value.id ? typeAdd : typeUpdate;
      fun(params).then((result) => {
        if (result.success) {
          message.success(!item.value.id ? '添加成功' : '修改成功');
          getFolderTree();
          proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR, value: { name: 'form' } }); // 取消弹层
          proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'archiveType' } }); // 更新table
        }
      });
    }
  });
getFolderTree();
// 获取档案类型
function getFolderTree() {
  const params = {
    name: state.searchName
  };
  state.treeData = [];
  typeTree(params).then((result) => {
    if (result.success) {
      state.treeData = [
        {
          name: '全部',
          id: '0',
          children: result.data
        }
      ];
    }
  });
}
// 点击档案类型
function handleNodeSelect(_: any, { node }) {
  const params = {
    parentId: node.id
  };
  state.selectParentId = node.id;
  directoryRef.value.getData(params);
}
// 添加档案类型
function handleAdd(record) {
  // 顶层可添加水印
  const showWater = !record.parentId;
  const dyAddQuestions: any = reactive(indexService.getAddQuestions('ADD', showWater));
  const params = { type: CODE_RULE.DALXBM };
  dyAddConfig.title = '添加档案类型';
  generateCode(params).then((res) => {
    if (res.success && res.data.length) {
      dyAddConfig.data.code = res.data[0];
    }
    proxy.$NotificationPubSub.pushParams({
      key: DYNAMICLAYERFORM,
      value: {
        config: dyAddConfig,
        form: dyAddQuestions,
        data: {
          parentId: record.id
        }
      }
    });
  });
}
// 编辑档案类型
function handleEdit(record) {
  // 第一层可编辑水印
  const showWater = record.parentId == '0';
  const dyAddQuestions: any = reactive(indexService.getAddQuestions('EDIT', showWater));
  dyAddConfig.title = '编辑档案类型';
  typeGet(record.id).then((result) => {
    if (result.success) {
      // 避免点击添加后取消再编辑数据用的是data里面的code
      dyAddConfig.data = {};
      proxy.$NotificationPubSub.pushParams({
        key: DYNAMICLAYERFORM,
        value: {
          config: dyAddConfig,
          form: dyAddQuestions,
          data: {
            code: result.data.code,
            name: result.data.name,
            id: result.data.id,
            parentId: result.data.parentId,
            watermarkingId: result.data.watermarkingId
          }
        }
      });
    }
  });
}
// 删除档案类型
function handleDelete(record) {
  typeDelete(record.id).then((result) => {
    if (result.success) {
      message.success('删除成功');
      getFolderTree();
      proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'archiveType' } }); // 更新table
    }
  });
}
// 更改状态时触发
function statusChange(record, value) {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确定',
    cancelText: '取消',
    content: '是否确定修改状态？',
    onOk() {
      const params = {
        id: record.id,
        status: value
      };
      typeUpdateStatus(params).then((result) => {
        if (result.success) {
          message.success('修改成功');
          directoryRef.value.getData({ parentId: state.selectParentId });
        }
      });
    }
  });
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
.title-warpper {
  .title-btn {
    float: right;
    display: none;
  }
  &:hover {
    .title-btn {
      display: inline-block;
    }
  }
}
:deep(.tree-warpper) {
  .ant-tree-switcher {
    line-height: 36px;
  }
  .ant-tree-node-content-wrapper {
    min-height: 36px;
    line-height: 36px;
    &.ant-tree-node-selected {
      background-color: #e5eefd;
      color: #005aea;
    }
  }
}
</style>
